package cat.sun.logic;

import java.util.Random;

import cat.sun.data.CellContent;
import cat.sun.data.CellState;

public class Pole 
{
	private int width;
	private int height;	
	private Cell [][] cells;
	
	public Pole(int height,int width)
	{
		this.cells = new Cell[height][width];
		this.height = height;
		this.width = width;
		for (int i=0;i<height;i++)
			for (int j = 0;j<width;j++)
				cells[i][j] = new Cell(i,j);
	}
	
	public void GenerateBombs(int bombs,int notx,int noty)
	{
		Random rand = new Random();
		int r = 0;
		while (r!=bombs)
		{
			int x = rand.nextInt(width);
			int y = rand.nextInt(height);
			if (x!=notx || y!=noty)
			{
				if (cells[y][x].makeBomb()) r++;
			}
		}
		for (int i = 0;i<height;i++)
			for (int j=0;j<width;j++)
			{
				if (cells[i][j].getCellContent() != CellContent.BOMB)
				{
					int k = 0;
					if (j-1>=0) if (cells[i][j-1].getCellContent() == CellContent.BOMB) k++;
					if (j+1<width) if (cells[i][j+1].getCellContent() == CellContent.BOMB) k++;
					if (i-1>=0) if (cells[i-1][j].getCellContent() == CellContent.BOMB) k++;
					if (i+1<height) if (cells[i+1][j].getCellContent() == CellContent.BOMB) k++;
					if (j-1>=0 && i-1>=0) if (cells[i-1][j-1].getCellContent() == CellContent.BOMB) k++;
					if (j-1>=0 && i+1<height) if (cells[i+1][j-1].getCellContent() == CellContent.BOMB) k++;
					if (j+1<width && i-1>=0) if (cells[i-1][j+1].getCellContent() == CellContent.BOMB) k++;
					if (j+1<width && i+1<height) if (cells[i+1][j+1].getCellContent() == CellContent.BOMB) k++;
					if (k>0) cells[i][j].makeNumber(k);
				}
			}
	}
	
	public void OpenAllBombs()
	{
		for (int i = 0;i<height;i++)
			for (int j=0;j<width;j++)
			{
				if (cells[i][j].getCellContent() == CellContent.BOMB  && !(cells[i][j].getState() == CellState.CHECKED)) cells[i][j].OpenCell();
			}
	}
	
	public void CheckAllBombs()
	{
		for (int i = 0;i<height;i++)
			for (int j=0;j<width;j++)
			{
				if (cells[i][j].getCellContent() == CellContent.BOMB  && !(cells[i][j].getState() == CellState.CHECKED)) cells[i][j].Checked();
			}
	}
	
	public void CrossAllBadFlags()
	{
		for (int i = 0;i<height;i++)
			for (int j=0;j<width;j++)
			{
				if ((cells[i][j].getCellContent() != CellContent.BOMB) && (cells[i][j].getState() == CellState.CHECKED))
					cells[i][j].CrossCheck();
			}
	}
	
	public void setRedBomb(int x,int y)
	{
		this.cells[y][x].setRedBomb();
	}
	
	public CellContent makeMove(int x,int y)
	{
		CellContent opened = this.cells[y][x].OpenCell();
		return opened;
	}
	
	public boolean Check(int x, int y)
	{
		return this.cells[y][x].Checked();
	}
	
	public int getHeight()
	{
		return this.height;
	}
	
	public int getWidth()
	{
		return this.width;
	}
	
	synchronized public Cell getCell(int x,int y)
	{
		return this.cells[y][x];
	}
	
}
